package cn.liontalk.service.impl;

import cn.liontalk.constant.Constant;
import cn.liontalk.dao.BrokerMessageDao;
import cn.liontalk.dao.OrderDao;
import cn.liontalk.entity.BrokerMessageLog;
import cn.liontalk.entity.Order;
import cn.liontalk.producer.RabbitmqOrderSender;
import cn.liontalk.service.OrderService;
import cn.liontalk.utils.FastJsonConvertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author ZhouZhe
 * @version 1.0
 * @description
 * @date 2018-12-13 20:54
 **/
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private BrokerMessageDao brokerMessageDao;

    @Autowired
    RabbitmqOrderSender rabbitmqOrderSender;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendOrderMessage(Order order) {
        Date orderTime = new Date();

        orderDao.insertOrder(order);


        // 插入消息记录表数据
        BrokerMessageLog brokerMessageLog = new BrokerMessageLog();
        // 消息唯一ID
        brokerMessageLog.setMessageId(order.getMessageId());
        // 保存消息整体 转为JSON 格式存储入库
        brokerMessageLog.setMessage(FastJsonConvertUtil.convertObjectToJSON(order));
        // 设置消息状态为0 表示发送中
        brokerMessageLog.setStatus("0");
        // 设置消息未确认超时时间窗口为 一分钟
        brokerMessageLog.setNextRetry(cn.liontalk.utils.DateUtil.addMinutes(orderTime, Constant.ORDER_TIMEOUT));
        brokerMessageLog.setCreateTime(new Date());
        brokerMessageLog.setUpdateTime(new Date());
        brokerMessageDao.insertBrokerMessageLog(brokerMessageLog);
        rabbitmqOrderSender.sendOrder(order);
    }
}
